/** 初始化敏感词库，将敏感词加入到HashMap中，构建DFA算法模型 **/
export default class SensitiveWordInit {
    constructor() {
    }

    public static initKeyWord(worlds: string): { [key: string]: any } {
        return SensitiveWordInit.addSensitiveWordToHashMap(worlds.split(","));
    }

    /**
     * 读取敏感词库，将敏感词放入Map中，构建一个DFA算法模型：<br>
     * 中 = {
     *      isEnd = 0
     *      国 = {<br>
     *      	 isEnd = 1
     *           人 = {isEnd = 0
     *                民 = {isEnd = 1}
     *                }
     *           男  = {
     *           	   isEnd = 0
     *           		人 = {
     *           			 isEnd = 1
     *           			}
     *           	}
     *           }
     *      }
     *  五 = {
     *      isEnd = 0
     *      星 = {
     *      	isEnd = 0
     *      	红 = {
     *              isEnd = 0
     *              旗 = {
     *                   isEnd = 1
     *                  }
     *              }
     *      	}
     *      }
     */
    private static addSensitiveWordToHashMap(worlds: string[]): { [key: string]: any } {
        let sensitiveWordMap: { [key: string]: any } = {};
        let key: string;
        let nowMap: { [key: string]: any };
        let newWorMap: { isEnd: string };
        let count: number = worlds.length;
        for (var idx: number = 0; idx < count; ++idx) {
            key = worlds[idx];
            nowMap = sensitiveWordMap;
            for (var i = 0; i < key.length; ++i) {
                let keyChar: string = key.charAt(i);       //转换成char型
                let wordMap = nowMap[keyChar];       //获取
                if (wordMap) {        //如果存在该key，直接赋值
                    nowMap = wordMap;
                } else {     //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = { isEnd: "0" }; //isEnd:"0" 不是最后一个
                    nowMap[keyChar] = newWorMap;
                    nowMap = newWorMap;
                }
                if (i == key.length - 1) {
                    nowMap["isEnd"] = "1"; //最后一个
                }
            }
        }
        return sensitiveWordMap;
    }
}


export class SensitivewordFilter {
    private sensitiveWordMap: { [key: string]: any };
    public static minMatchTYpe: number = 1;      //最小匹配规则
    public static maxMatchType: number = 2;      //最大匹配规则
    constructor() {

    }

    public initKeyWord(worlds: string): void {
        this.sensitiveWordMap = SensitiveWordInit.initKeyWord(worlds);
    }

    /**
     * 检查文字中是否包含敏感字符，检查规则如下：<br>
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return，如果存在，则返回敏感词字符的长度，不存在返回0
     */
    public CheckSensitiveWord(txt: string, beginIndex: number, matchType: number = 1): number {
        let flag: boolean = false;    //敏感词结束标识位：用于敏感词只有1位的情况
        let matchFlag: number = 0;     //匹配标识数默认为0
        let word: string = "";
        let nowMap = this.sensitiveWordMap;
        for (var i: number = beginIndex; i < txt.length; ++i) {
            word = txt.charAt(i);
            nowMap = nowMap[word];     //获取指定key
            if (nowMap) {     //存在，则判断是否为最后一个
                matchFlag++;     //找到相应key，匹配标识+1 
                if (nowMap["isEnd"] == "1") {       //如果为最后一个匹配规则,结束循环，返回匹配标识数
                    flag = true;       //结束标志位为true   
                    if (SensitivewordFilter.minMatchTYpe == matchType) {    //最小规则，直接返回,最大规则还需继续查找
                        break;
                    }
                }
            }
            else {     //不存在，直接返回
                break;
            }
        }
        if (matchFlag < 2 || !flag) {        //长度必须大于等于1，为词 
            matchFlag = 0;
        }
        return matchFlag;
    }

    /**
     * 判断文字是否包含敏感字符
     * @param txt  文字
     * @param matchType  匹配规则&nbsp;1：最小匹配规则，2：最大匹配规则
     * @return 若包含返回true，否则返回false
     */
    public isContaintSensitiveWord(txt: string, matchType: number = 1): boolean {
        let flag: boolean = false;
        for (var i: number = 0; i < txt.length; ++i) {
            let matchFlag: number = this.CheckSensitiveWord(txt, i, matchType); //判断是否包含敏感字符
            if (matchFlag > 0) {    //大于0存在，返回true
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 获取文字中的敏感词
     * @param txt 文字
     * @param matchType 匹配规则&nbsp;1：最小匹配规则，2：最大匹配规则
     * @return
     */
    public getSensitiveWord(txt: string, matchType: number = 1): string[] {
        let sensitiveWordList: string[] = [];
        for (var i: number = 0; i < txt.length; ++i) {
            let length: number = this.CheckSensitiveWord(txt, i, matchType);    //判断是否包含敏感字符
            if (length > 0) {    //存在,加入list中
                sensitiveWordList.push(txt.substring(i, i + length));
                i = i + length - 1;    //减1的原因，是因为for会自增
            }
        }
        return sensitiveWordList;
    }

    /**
     * 替换敏感字字符
     * @param txt
     * @param matchType
     * @param replaceChar 替换字符，默认*
     */
    public replaceSensitiveWord(txt: string, matchType: number = 1, replaceChar: string = "*"): string {
        let resultTxt: string = txt;
        let arr_worlds: string[] = this.getSensitiveWord(txt, matchType);     //获取所有的敏感词
        let word: string;
        let replaceString: string;
        let len: number = arr_worlds.length;
        for (var idx: number = 0; idx < len; ++idx) {
            word = arr_worlds[idx];
            replaceString = this.getReplaceChars(replaceChar, word.length);
            resultTxt = resultTxt.replace(word, replaceString);
        }
        return resultTxt;
    }

    /**
     * 获取替换字符串 
     * @param replaceChar
     * @param length
     * @return
     */
    private getReplaceChars(replaceChar: string, length: number): string {
        let resultReplace: string = replaceChar;
        for (var i: number = 1; i < length; ++i) {
            resultReplace += replaceChar;
        }
        return resultReplace;
    }

    public static test(str: string): void {
        let filter: SensitivewordFilter = new SensitivewordFilter();
        filter.initKeyWord("色情,贪腐,三级片,红客联盟,饲养基地,法轮功,自杀,手机卡复制器");
        // trace("敏感词的数量：" + filter.sensitiveWordMap.);
        console.log("待检测语句字数：" + str.length);
        let beginTime: number = this.getCurTimer();
        let arr_worlds: string[] = filter.getSensitiveWord(str, 2);
        let endTime: number = this.getCurTimer();
        console.log("语句中包含敏感词的个数为：" + arr_worlds.length + "。包含：" + arr_worlds);
        console.log("总共消耗时间为：" + (endTime - beginTime));
        console.log("屏蔽后文本为：" + filter.replaceSensitiveWord(str, 1, "*"));
    }

    private static getCurTimer() {
        return new Date().getTime();
    }

}

/**
    * 使用方法
    */
    // let str: string = "自杀 太多的伤感情怀也许只局限于饲养基地 荧幕中的情节，主人公尝试着去用某种方式渐渐的很潇洒地释自杀指南怀那些自己经历的伤感。"
    //         + "然后法轮功 我们的扮演的角色就是跟随着主人公的喜红客联盟 怒哀乐而过于牵强的把自己的情感也附加于银幕情节中，然后感动就流泪，"
    //         + "难过就躺在某一个人的怀里尽情的阐述心扉或者手机卡复制器一个人一杯红酒一部电影在夜三级片 深人静的晚上，关上电话静静的发呆着。";
    //     SensitivewordFilter.test(str);